/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.isseiaoki.simplecropview.slice;

import com.isseiaoki.simplecropview.CropImageView;
import com.isseiaoki.simplecropview.ResourceTable;
import io.reactivex.Observable;
import io.reactivex.SingleSource;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.global.resource.ResourceManager;
import ohos.media.image.ImagePacker;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.utils.net.Uri;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

/**
 * rxjava示例
 */
public class RxJavaCropImageAbilitySlice extends AbilitySlice {

    private CropImageView cropImageView;
    private Uri uri = null;
    private Image image1 = null;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_rxjava_crop_image);
        cropImageView = (CropImageView) findComponentById(ResourceTable.Id_cropImageView);
        image1 = (Image) findComponentById(ResourceTable.Id_img_test);
        ResourceManager resourceManager = getResourceManager();
        File file = null;
        try {
            file = new File(getContext().getFilesDir() + "/test11.png");
            if (!file.exists()) {
                file.createNewFile();
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            sourceOptions.formatHint = "image/png";
            ImageSource imageSource = ImageSource.create(resourceManager.getResource(ResourceTable.Media_sample1), sourceOptions);
            ImagePacker imagePacker = ImagePacker.create();
            ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
            packingOptions.format = "image/jpeg";
            packingOptions.quality = 90;
            imagePacker.initializePacking(bos, packingOptions);
            imagePacker.addImage(imageSource);
            imagePacker.finalizePacking();
            bos.flush();
            bos.close();
            uri = Uri.getUriFromFile(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        rxjavaLoad();
        Button btnCrop = (Button) findComponentById(ResourceTable.Id_btn_crop);
        btnCrop.setClickedListener(component -> rxjavaCrop());
        Button btnFixImag = (Button) findComponentById(ResourceTable.Id_btn_fiximage);
        Button btnSqure = (Button) findComponentById(ResourceTable.Id_btn_squre);
        Button btn34 = (Button) findComponentById(ResourceTable.Id_btn_3_4);
        Button btn43 = (Button) findComponentById(ResourceTable.Id_btn_4_3);
        Button btnFree = (Button) findComponentById(ResourceTable.Id_btn_free);
        Button btnCircle = (Button) findComponentById(ResourceTable.Id_btn_circle);

        btnFixImag.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                image1.setVisibility(Component.HIDE);
                cropImageView.setVisibility(Component.VISIBLE);
                cropImageView.setCropMode(CropImageView.CropMode.FIT_IMAGE);
            }
        });

        btnSqure.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                image1.setVisibility(Component.HIDE);
                cropImageView.setVisibility(Component.VISIBLE);
                cropImageView.setCropMode(CropImageView.CropMode.SQUARE);
            }
        });

        btn34.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                image1.setVisibility(Component.HIDE);
                cropImageView.setVisibility(Component.VISIBLE);
                cropImageView.setCropMode(CropImageView.CropMode.RATIO_3_4);
            }
        });

        btn43.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                image1.setVisibility(Component.HIDE);
                cropImageView.setVisibility(Component.VISIBLE);
                cropImageView.setCropMode(CropImageView.CropMode.RATIO_4_3);
            }
        });

        btnFree.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                image1.setVisibility(Component.HIDE);
                cropImageView.setVisibility(Component.VISIBLE);
                cropImageView.setCropMode(CropImageView.CropMode.FREE);
            }
        });

        btnCircle.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                image1.setVisibility(Component.HIDE);
                cropImageView.setVisibility(Component.VISIBLE);
                cropImageView.setCropMode(CropImageView.CropMode.CIRCLE);
            }
        });
    }

    private void rxjavaLoad() {
        Observable<Integer> observable = Observable.create(emitter -> {
            cropImageView.load(uri).executeAsCompletable();
        });
        observable.subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) throws Exception {

            }
        });
    }

    private void rxjavaCrop() {
        String uriPath = "file://"+getContext().getFilesDir()+"/test22.jpg";
        Observable<Integer> observable = Observable.create(emitter -> {
            cropImageView.crop(uri)
                    .executeAsSingle()
                    .flatMap(new Function<PixelMap, SingleSource<Uri>>() {
                        @Override
                        public SingleSource<Uri> apply(@io.reactivex.annotations.NonNull PixelMap bitmap)
                                throws Exception {
                            cropImageView.getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
                                @Override
                                public void run() {
                                    image1.setPixelMap(bitmap);
                                    image1.setVisibility(Component.VISIBLE);
                                    cropImageView.setVisibility(Component.INVISIBLE);
                                }
                            });
                            return cropImageView.save(bitmap)
                                    .executeAsSingle(Uri.parse(uriPath));
                        }
                    })
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@io.reactivex.annotations.NonNull Disposable disposable)
                                throws Exception {
                        }
                    })
                    .doFinally(new Action() {
                        @Override
                        public void run() throws Exception {
                        }
                    })
                    .subscribeOn(Schedulers.newThread())
                    .subscribe(new Consumer<Uri>() {
                        @Override
                        public void accept(@io.reactivex.annotations.NonNull Uri uri11) throws Exception {
                            emitter.onComplete();

                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(@io.reactivex.annotations.NonNull Throwable throwable)
                                throws Exception {
                            emitter.onComplete();
                        }
                    });
        });

        observable.subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) throws Exception {

            }
        });
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}
